import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
NProgress.configure({ // NProgress Configuration
  showSpinner: false
})

import {pvLog} from '@/srv/utils/pvLog';

function initHooks(router) {
  router.beforeEach(async (to, from, next) => {
    // start progress bar
    NProgress.start()

    const {
      title
    } = to.meta;
    document.title = title ? `ZZGIS - ${title}` : "ZZGIS"

    return next()

    // determine whether the user has logged in
    const token = getToken()
    // console.log(token)

    if (!token) {
      NProgress.done()
      return logout()
    }

    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
      return login()
    }

    // determine whether the user has obtained his permission roles through getInfo
    let roleArr = getRoles()
    const hasRoles = roleArr && roleArr.length > 0
    if (hasRoles) {
      return next()
    } else {

      try {
        // get user info
        // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
        const {
          roles
        } = await getUserinfo()
        // console.log(roles)

        // const accessRoutes = await store.dispatch('permission/generateRoutes', roles)

        // dynamically add accessible routes
        // router.addRoutes(accessRoutes)

        // resetAlive(router)

        // hack method to ensure that addRoutes is complete
        // set the replace: true, so the navigation will not leave a history record
        next({
          ...to,
          replace: true
        })
      } catch (error) {
        NProgress.done()
        // logout()
      }
    }
  })

  router.afterEach((to, from, failure) => {
    if (!failure) {
      NProgress.done()
      pvLog(from, to)
    }
  })
}

export {
  initHooks
}
